package com.rongeadi.app.jinrirong.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.rongeadi.app.R;
import com.rongeadi.app.jinrirong.common.base.BaseActivity;
import com.rongeadi.app.jinrirong.config.UserManager;
import com.rongeadi.app.push.ExampleUtil;
import com.rongeadi.app.push.LocalBroadcastManager;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;


public class SplashActivity extends BaseActivity {

    //页面跳转延迟时长
    private static final long VALUE_DELAYED_TIME = 1400;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initView() {
        requestTranslucentStatusBar(Color.TRANSPARENT, false);
    }

    @Override
    protected void initData() {
        AndPermission.with(this).permission(Manifest.permission.ACCESS_COARSE_LOCATION)
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        //拒绝
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startMainActivity();
                            }
                        }, VALUE_DELAYED_TIME);
                    }
                })
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        //通过
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startMainActivity();
                            }
                        }, VALUE_DELAYED_TIME);
                    }
                }).start();
    }

    /**
     * 启动主页面
     */
    private void startMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        init();
        registerMessageReceiver();
        finish();
    }


    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.rongeadi.app.jinrirong.activity.MainActivity";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        JPushInterface.init(getApplicationContext());

        Set<String> tags = new HashSet<String>();
        //这里可以设置你要推送的人，一般是用户uid 不为空在设置进去 可同时添加多个
        String tag = UserManager.getInstance().getUid();//UUID.randomUUID().toString().replaceAll("-", "");
        if (!TextUtils.isEmpty(UserManager.getInstance().getUid())) {
            tags.add(tag);//设置tag
        }
        JPushInterface.setAliasAndTags(this, tag, tags, (code, alias, tags1) -> {
            String logs;
            switch (code) {
                case 0:
                    //这里可以往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    //UserUtils.saveTagAlias(getHoldingActivity(), true);
                    logs = "Set tag and alias success极光推送别名" + tag+ "设置成功tags[" + Arrays.toString(tags.toArray()) + "]";
                    Log.e("TAG", logs);
                    break;
                case 6002:
                    //极低的可能设置失败 我设置过几百回 出现3次失败 不放心的话可以失败后继续调用上面那个方面 重连3次即可 记得return 不要进入死循环了...
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.极光推送别名设置失败，60秒后重试";
                    Log.e("TAG", logs);
                    break;
                default:
                    logs = "极光推送设置失败，Failed with errorCode = " + code;
                    Log.e("TAG", logs);
                    break;
            }
        });
    }
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                Log.d("1111111111111111111111", "onReceive: ."+messge );
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    Toast.makeText(context, showMsg.toString(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
            }
        }
    }

}
